package top.codef.crypt.aes;

import java.security.SecureRandom;
import java.security.Security;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import org.bouncycastle.jce.provider.BouncyCastleProvider;

import top.codef.crypt.CryptAlgorithm;

public class AESKeyPair {

	private SecretKey secretKey;

	private String cryptAlgorithm = "AES";

	private AESKeyPair() {

	}

	private AESKeyPair(SecretKey secretKey, String cry) {
		this.secretKey = secretKey;
		this.cryptAlgorithm = cry;
	}

	public static AESKeyPair instance(byte[] key) {
		Security.addProvider(new BouncyCastleProvider());
		SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
		AESKeyPair aesKeyPair = new AESKeyPair(secretKeySpec, CryptAlgorithm.AES.getAlgorithm());
		return aesKeyPair;
	}

	public static AESKeyPair instance(byte[] key, AesAlgorithm cryptAlgorithm) {
		Security.addProvider(new BouncyCastleProvider());
		SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
		AESKeyPair aesKeyPair = new AESKeyPair(secretKeySpec, cryptAlgorithm.getAlgorithm());
		return aesKeyPair;
	}

	public byte[] encrypt(byte[] content) throws Exception {
		Cipher cipher = Cipher.getInstance(cryptAlgorithm);
		cipher.init(Cipher.ENCRYPT_MODE, secretKey);
		byte[] secContent = cipher.doFinal(content);
		return secContent;
	}

	public byte[] decrypt(byte[] secContent) throws Exception {
		Cipher cipher = Cipher.getInstance(cryptAlgorithm);
		cipher.init(Cipher.DECRYPT_MODE, secretKey);
		byte[] content = cipher.doFinal(secContent);
		return content;
	}

	public static byte[] genericKey(int size) throws Exception {
		KeyGenerator generator = KeyGenerator.getInstance(CryptAlgorithm.AES.getAlgorithm());
		generator.init(size, SecureRandom.getInstanceStrong());
		SecretKey secretKey = generator.generateKey();
		return secretKey.getEncoded();
	}
}
